import mss_format from '../utility/mss-format';

/**
 * 倒计时控件
 */
Component({
	/**
	 * 组件的属性列表
	 */
	options: {
	},
	properties: {
		auto: String,
		itv: Number,
		timer: {
			type: Number,
			value: 0
		},
		timer_str: {
			type: String,
			value: ''
		},
		wid: String
	},

	/**
	 * 组件的初始数据
	 */
	data: {

	},

	/**
	 * 组件的方法列表
	 */
	attached() {
		const _t = this;
		if (_t.data.auto) {
			_t.data.itv = setInterval(() => {
				_t.setData({
					timer_str: mss_format(_t.data.timer, 0, 1)
				});
				_t.data.timer = _t.data.timer - 1000;
				if (_t.data.timer < 0) {
					clearInterval(_t.data.itv);
					this.triggerEvent('fdwe-timestop', { wid: _t.data.wid }, { bubbles: true });
					return;
				}
			}, 1000);
		} else {
			_t.setData({
				timer_str: mss_format(_t.data.timer, 0, 1)
			});
		}
	},
	methods: {
		refresh(timer: number) {
			const _t = this;
			if (_t.data.itv) {
				clearInterval(_t.data.itv);
			}
			_t.data.timer = timer;
			_t.data.itv = setInterval(() => {
				_t.setData({
					timer_str: mss_format(_t.data.timer, 0, 1)
				});
				_t.data.timer = _t.data.timer - 1000;
				if (_t.data.timer < 0) {
					clearInterval(_t.data.itv);
					this.triggerEvent('fdwe-timestop', { wid: _t.data.wid }, { bubbles: true });
					return;
				}
			}, 1000);
		},
		pause() {
			clearInterval(this.data.itv);
		},
		continue() {
			this.refresh(this.data.timer);
		},
		stop(text: string) {
			clearInterval(this.data.itv);
			this.setData({
				timer_str: text
			});
		}
	}
});
